﻿
namespace MyFurion.Application.Controller
{
    /// <summary>
    /// 角色
    /// </summary>
    public class RoleController:IDynamicApiController
    {
        private readonly RoleRepository _repository;
        private readonly UserRoleRepository _userRoleRepository;
        private readonly RoleMenuRepository _roleMenuRepository;
        private readonly OrgPerRepository _perRepository;
        public RoleController(RoleRepository userRepository, UserRoleRepository userRoleRepository, RoleMenuRepository roleMenuRepository, OrgPerRepository perRepository)
        {
            _repository = userRepository;
            _userRoleRepository= userRoleRepository;
            _roleMenuRepository= roleMenuRepository;
            _perRepository= perRepository;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("add")]
        public async Task Add(RoleInfoAdd input)
        {
            if (!Enum.IsDefined(typeof(EnumOrgAuthority), input.OrgAuthority))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined, "机构数据权限"));
            }
            if (!Enum.IsDefined(typeof(EnumStatus), input.Status))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined, "状态"));
            }
            bool isExists = await _repository.DataExists(input.RoleCode);
            if (isExists)
            {
                throw Oops.Oh(ErrorMsgConst.ExistError);
            }
            var model = input.Adapt<RoleInfo>();
            bool result=await _repository.Add(model);
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.SaveError);
            }
            else
            {
                if (input.OrgAuthority == EnumOrgAuthority.CustomOrg)
                {
                    await _perRepository.GrantOrg(model.Id, input.OrgAuthorityIds);
                }   
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task Update(RoleInfoUpdate input)
        {
            if (!Enum.IsDefined(typeof(EnumOrgAuthority), input.OrgAuthority))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined, "机构数据权限"));
            }
            if (!Enum.IsDefined(typeof(EnumStatus), input.Status))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined, "状态"));
            }
            bool isExists = await _repository.DataExists(input.RoleCode, input.Id);
            if (isExists)
            {
                throw Oops.Oh(ErrorMsgConst.ExistError);
            }
            var model =await _repository.GetEntityById(input.Id);
            if (model == null)
            {
                throw Oops.Oh(ErrorMsgConst.NoRecord);
            }
            model.RoleCode = input.RoleCode;
            model.RoleName= input.RoleName;
            model.Status= input.Status;
            model.OrgAuthority= input.OrgAuthority;
            bool result = await _repository.Update(model);
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.SaveError);
            }
            else
            {
                await _perRepository.GrantOrg(input.Id, input.OrgAuthorityIds);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpDelete("delete")]
        public async Task Delete([FromQuery]BaseIdInput input)
        {
            //判断是有有用户已关联角色信息
            bool isLink =await _userRoleRepository.IsExists(it=>it.RoleId==input.Id);
            if (isLink)
            {
                throw Oops.Oh("该角色已与用户关联，不可删除");
            }
            bool result = await _repository.DeleteById(input.Id);
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.DeleteError);
            }
            else
            {
                await _roleMenuRepository.DeleteByWhere(it=>it.RoleId==input.Id);
                await _perRepository.DeleteByWhere(it => it.RoleId == input.Id);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpDelete("batchDelete")]
        public async Task BatchDelete([FromQuery]BaseIdsInput input)
        {
            var roleUserData = await _userRoleRepository.GetListByWhere(it => input.Ids.Contains(it.RoleId));
            if (roleUserData.Any())
            {
                var rolIds = roleUserData.Select(g => g.RoleId).Distinct().ToList();
                var roleData = await _repository.GetListByWhere(it=>rolIds.Contains(it.Id));
                string roleName = String.Join(",", roleData.Select(g => g.RoleName));
                throw Oops.Oh($"角色{roleName}已与用户关联，不可删除");
            }
            bool result = await _repository.DeleteByWhere(it=>input.Ids.Contains(it.Id));
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.DeleteError);
            }
            else
            {
                await _roleMenuRepository.DeleteByWhere(it =>input.Ids.Contains(it.RoleId));
                await _perRepository.DeleteByWhere(it => input.Ids.Contains(it.RoleId));
            }
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("setStatus")]
        public async Task ModifyStatus(SetStatusInfo input)
        {
            if (!Enum.IsDefined(typeof(EnumStatus), input.Status))
            {
                throw Oops.Oh(String.Format(ErrorMsgConst.NotDefined, "状态"));
            }
            bool result = await _repository.Update(it => it.Id == input.Id, it => new RoleInfo() { Status = input.Status });
            if (!result)
            {
                throw Oops.Oh(ErrorMsgConst.StatusError);
            }
        }
        /// <summary>
        /// 配置菜单权限
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("grantMenuPer")]
        public async Task GrantMenuRight(RoleMenuRight input)
        {
            bool result = await _roleMenuRepository.GrantMenu(input.RoleId,input.MenuIds);
            if (!result)
            {
                throw Oops.Oh("菜单授权失败");
            }
        }
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("page")]
        public async Task<PageResult<RoleInfo>>QueryPage(RoleInfoPage input)
        {
            return await _repository.GetPageList(input);
        }
        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("list")]
        public async Task<List<RoleInfo>> QueryList(RoleInfoPage input)
        {
            return await _repository.GetDataList(input);
        }
        /// <summary>
        /// 根据id获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<RoleInfo> GetDetail(long id)
        {
            return await _repository.GetEntityById(id);
        }
        /// <summary>
        /// 获取角色机构权限Id集合
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        [HttpGet("getOrgPerIds")]
        public async Task<List<long>> GetOrgPer(long id)
        {
            return await _perRepository.GetRoleOrgIds(new List<long> { id });
        }
        /// <summary>
        /// 获取角色机构权限集合
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        [HttpGet("getRoleOrgPer")]
        public async Task<List<OrgInfo>> GetRoleOrgPer(long id)
        {
            return await App.GetService<OrgRepository>().GetRoleOrgPer(id);
        }
        /// <summary>
        /// 获取角色菜单权限Id集合
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        [HttpGet("getMenuPerIds")]
        public async Task<List<long>> GetMenuPer(long id)
        {
            return await _roleMenuRepository.GetRoleMenuIdList(new List<long> { id });
        }
        /// <summary>
        /// 获取角色菜单权限集合
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        [HttpGet("getRoleMenuPer")]
        public async Task<List<MenuInfo>> GetRoleMenuPer(long id)
        {
            return await App.GetService<MenuRepository>().GetRoleMenuPer(id);
        }
    }
}
